package com.paper.check.analyzer.service;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.model.Lexeme;


/**
 * Description: TODO <br/>
 * 
 * @date: 2016年4月8日 下午5:29:47
 * @version: 1.0
 * @since: JDK 1.7
 */
public class TextServiceImpl implements TextService {
    private static final Logger logger = LoggerFactory.getLogger(TextServiceImpl.class);
    IKSegmenter ikSmart = new IKSegmenter(new StringReader(""), true);
    IKSegmenter ik = new IKSegmenter(new StringReader(""), false);

    @Override
    public List<Lexeme> analyzer(String str) {
        return analyzerSmart(str);
    }

    @Override
    public List<Lexeme> analyzer(String str, boolean smart) {
        if (smart) {
            return analyzerSmart(str);
        } else {
            return analyzerNotSmart(str);
        }
    }

    private List<Lexeme> analyzerSmart(String str) {
        List<Lexeme> rs = new ArrayList<>();
        ikSmart.reset(new StringReader(str));
        Lexeme l = null;
        try {
            while ((l = ikSmart.next()) != null) {
                rs.add(l);
            }
        } catch (IOException e) {
            logger.error("分词异常", e);
        }
        logger.debug(str + " smart分词： " + rs.toString());
        return rs;
    }

    private List<Lexeme> analyzerNotSmart(String str) {
        List<Lexeme> rs = new ArrayList<>();
        ik.reset(new StringReader(str));
        Lexeme l = null;
        try {
            while ((l = ik.next()) != null) {
                rs.add(l);
            }
        } catch (IOException e) {
            logger.error("分词异常", e);
        }
        logger.info(str + " 分词： " + rs.toString());
        return rs;
    }

}
